<template>
	<base-popup-small titleT="nickname.title">
		<div class="py-5">
			<base-input :label="$t('nickname.PH')" v-model="nickname" />
			<base-input-rule :title="$t('nickname.ruleTitle')" :options="nicknameRule" />
			<base-button
				class="mt-5"
				type="primary"
				:disabled="submitDisabled"
				:loading="loading"
				@click="onSubmit">
				{{ $t('action.save') }}
			</base-button>
		</div>
	</base-popup-small>
</template>

<script lang="ts" setup>
import { BasePopupSmall, BaseInputRule, BaseInput, BaseButton } from '@/components/base'
import { ref, computed, watch } from 'vue'
import { useProfileStore } from '@/store'
import { hasSpace, hasSpecialChar } from '@/utils'
import { setNickname } from '@/api/profile'
import { useRequest } from '@/hooks'

const emits = defineEmits(['success'])

const profileStore = useProfileStore()

const nickname = ref('')

const nicknameRule = computed(() => {
	const nicknameLength = nickname.value.length
	const lengthValid = nicknameLength >= 4 && nicknameLength <= 16
	const charValid = !hasSpecialChar(nickname.value)
	const spaceValid = !!nickname.value && !hasSpace(nickname.value)
	return [
		{
			textT: 'nickname.ruleLength',
			valid: lengthValid
		},
		{
			textT: 'nickname.ruleChar',
			valid: charValid
		},
		{
			textT: 'nickname.ruleSpace',
			valid: spaceValid
		}
	]
})

const nicknameError = computed(() => {
	return nicknameRule.value.some((item) => !item.valid)
})

const submitDisabled = computed(() => !!nicknameError.value)

const { run, loading } = useRequest(setNickname, {
	showSuccess: true,
	showError: true,
	onSuccess: () => {
		profileStore.getUserInfo()
		emits('success')
	}
})

const onSubmit = () => {
	run({
		nickname: nickname.value
	})
}

watch(
	() => profileStore.userInfo?.nickName,
	() => {
		nickname.value = profileStore.userInfo?.nickName || ''
	},
	{
		immediate: true
	}
)
</script>
